import numpy as np
import matplotlib.pyplot as plt


# 定义逻辑斯蒂映射函数
def logistic_map(r, x):
    return r * x * (1 - x)


# 生成分叉图数据
def bifurcation_data(r_min=2.4, r_max=4.0, r_steps=1000, iterations=1000, last=1000):
    r_values = np.linspace(r_min, r_max, r_steps)
    x = np.random.random()  # 随机初始值
    bifurcation = []

    for r in r_values:
        # 迭代前 `iterations` 次（让系统稳定）
        for _ in range(iterations):
            x = logistic_map(r, x)

        # 记录后面 `last` 次的 x 值
        for _ in range(last):
            x = logistic_map(r, x)
            bifurcation.append((r, x))

    return np.array(bifurcation)


# 计算分叉图数据
bifurcation = bifurcation_data()

# 绘制分叉图
plt.figure(figsize=(10, 6))
plt.scatter(bifurcation[:, 0], bifurcation[:, 1], s=0.2, c='y', marker='.', alpha=0.1)
plt.title("Logistic Map Bifurcation Diagram")
plt.xlabel("r (Control Parameter)")
plt.ylabel("x (Population)")
plt.grid(True, alpha=0.3)
plt.show()
